#pragma once
#include <string>
#include <iostream>
#include <pthread.h>
#include <functional>
#include <cstring>
#include <cerrno>

void f()
{
    std::cout << "this is func" << std::endl;
    return;
}

namespace wgm
{
    static int cnt = 1;
    class Thread
    {
        using func_t = std::is_function<void()>;
    public:
        Thread()
            : _ret(nullptr), _detach(false), _run(false)
        {
            int n = pthread_create(&_tid, nullptr, routine, this);
            if(n != 0)
            {
                perror("创建线程失败，需要重新创建！");
                exit(EXIT_FAILURE);
            }
            else
            {
                std::cout << "创建成功，开始执行程序!" << std::endl;
            }
            _name = std::string("thread") + std::to_string(cnt++);
        }

        void Detach()
        {
            if(_detach) return;
            _detach = true;
            if(!_run) return;
            int n = pthread_detach(_tid);
            if(n != 0)
            {
                std::cout << "线程分离失败, 程序退出!" << std::endl;
                exit(EXIT_FAILURE);
            }
            else
            {
                std::cout << "线程分离成功！" << std::endl;
            }
        }

        bool Stop()
        {
            if(_run)
            {
                int n = pthread_cancel(_tid);
                if(n != 0)
                {
                    std::cerr << "create thread error" << 
                    strerror(n) << std::endl;
                    return false;
                }
                else
                {
                    _run = false;
                    std::cout << _name << " stop" << std::endl;
                    return true;
                }
            }
            return true;
        }

        void Join()
        {
            if(_detach) 
            {
                std::cout << "当前进程已经被分离，不能继续等待" << std::endl;
                return;
            }
            if(!_run)
            {
                std::cout << "当前线程还没有执行" << std::endl;
                return;
            }
            _run = false;
            int n = pthread_join(_tid, (void**)&_ret);
            if(n != 0)
            {
                std::cout << "等待失败！" << std::endl;
            }
            else
            {
                std::cout << "等待成功!" <<  std::endl;
            }
        }

        ~Thread()
        {
            std::cout << "析构函数调用！" << std::endl;
            if(!_detach)
                Join();
        }

    private:
        static void* routine(void *args)
        {
            Thread *self = static_cast<Thread *>(args);
            self->EnableRun();
            if(self->_detach)
            {
                self->Detach();
            }
        }

        void EnableRun()
        {
            _run = true;
        }

    private:
        pthread_t _tid;
        std::string _name;
        void *_ret;
        bool _detach;
        bool _run;
        func_t _func;
    };
}
